<template>
  <el-dialog
    v-model="visible"
    title="修改API业务规则配置"
    width="500px"
    @close="resetForm"
  >
    <el-form ref="userFormRef" :model="form" :rules="rules">
      <el-form-item label="API调用超时时间（秒）" prop="timeoutSeconds">
        <el-input-number
          v-model="form.timeoutSeconds"
          :min="1"
          :step="1"
          step-strictly
        />
      </el-form-item>
      <el-form-item label="重试间隔（秒）" prop="retryIntervalSeconds">
        <el-input-number
          v-model="form.retryIntervalSeconds"
          :min="1"
          :step="1"
          step-strictly
        />
      </el-form-item>
      <el-form-item label="最大重试次数" prop="maxRetryAttempts">
        <el-input-number
          v-model="form.maxRetryAttempts"
          :min="1"
          :step="1"
          step-strictly
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button :loading="submitLoading" type="primary" @click="submitForm">
        确认
      </el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { setAdminApiRules } from "@/api/adminDynamicApi";
import { message } from "@/utils/message";

interface UserForm {
  timeoutSeconds: number;
  maxRetryAttempts: number;
  retryIntervalSeconds: number;
}
const visible = ref(false);

const form = reactive<UserForm>({
  timeoutSeconds: 0,
  maxRetryAttempts: 0,
  retryIntervalSeconds: 0
});

const emits = defineEmits(["refresh"]);

const rules: FormRules = {
  timeoutSeconds: [
    {
      required: true,
      message: "请输入超时时间",
      trigger: "blur"
    }
  ],
  maxRetryAttempts: [
    {
      required: true,
      message: "请输入最大重试次数",
      trigger: "blur"
    }
  ],
  retryIntervalSeconds: [
    {
      required: true,
      message: "请输入重试间隔时间",
      trigger: "blur"
    }
  ]
};

const userFormRef = ref<FormInstance>();
const submitLoading = ref(false);
const submitForm = () => {
  userFormRef.value?.validate(async valid => {
    if (valid) {
      try {
        submitLoading.value = true;
        await setAdminApiRules(form);
        message("更新成功", { type: "success" });
        visible.value = false;
        emits("refresh");
      } catch (error) {
        console.error(error);
      } finally {
        submitLoading.value = false;
      }
    }
  });
};

const resetForm = () => {
  userFormRef.value?.resetFields();
  userFormRef.value?.clearValidate();
};
const open = ({
  apiCallTimeoutSeconds,
  maxRetryAttempts,
  retryIntervalSeconds
}) => {
  form.timeoutSeconds = apiCallTimeoutSeconds;
  form.maxRetryAttempts = maxRetryAttempts;
  form.retryIntervalSeconds = retryIntervalSeconds;
  visible.value = true;
};

defineExpose({ open });
</script>
